#!/bin/bash

#
# Copyright © 2015 Cask Data, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not
# use this file except in compliance with the License. You may obtain a copy of
# the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations under
# the License.
#

# prerm script for <%= project %>
set -e

package_name="<%= project %>"
version="<%= @version %>"

case "$1" in
    remove)
      if stat -t /opt/cdap/$package_name/conf/*-env.sh >/dev/null 2>&1 ; then
        find -L /opt/cdap/$package_name/conf -name '*-env.sh' | xargs -n1 basename | sed 's/-env.sh//' | while read svcname; do
          # stop each service
          if [ -x "/etc/init.d/cdap-$svcname" ]; then
            invoke-rc.d cdap-$svcname stop || :
          fi
          if [ -h "/opt/cdap/$package_name/bin/svc-$svcname" ]; then
            unlink /opt/cdap/$package_name/bin/svc-$svcname > /dev/null 2>&1 ||:
          fi
          rm -f /opt/cdap/$package_name/version ||:
        done
      fi
    ;;

    upgrade|deconfigure)
      if stat -t /opt/cdap/$package_name/conf/*-env.sh >/dev/null 2>&1 ; then
        find -L /opt/cdap/$package_name/conf -name '*-env.sh' | xargs -n1 basename | sed 's/-env.sh//' | while read svcname; do
          if [ -h "/opt/cdap/$package_name/bin/svc-$svcname" ]; then
            unlink /opt/cdap/$package_name/bin/svc-$svcname > /dev/null 2>&1 ||:
          fi
          rm -f /opt/cdap/$package_name/version ||:
          # services will be condrestarted on new package postinstall
        done
      fi
    ;;

    failed-upgrade)
    ;;

    *)
        echo "prerm called with unknown argument \`$1'" >&2
        exit 1
    ;;
esac

exit 0
